Overview

Testing is the process of validating the result of an operation against an expected output. Django’s test framework internally uses Python’s unit test package.

In this exercise, you will write the unit tests for satisfactory behavior of models and the views you have defined in the Menu API.

Scenario

In your restaurant app, you already have built the Menu API and Booking API . You will write the model test in test_models.py and view test in test_views.py files .

Step 1

When you create the app, an empty test.py file is created in the app package folder. Go ahead and delete it.

In the project container folder, create a new folder with the name tests .

Step 2

Open the definition of the Menu model class.

Add a __str__() method that returns a string representation of the model instance.

#add the following method in Menu class
def __str__(self):
        return f'{self.title} : {str(self.price)}'

Tip: As you have made changes to the model, you must run the migrations to sync the changes.

Step 3

Create a new file in the tests folder named test-models.py .

Import the TestCase class from the django.tests module.

Use it as base and declare a test class, for example, MenuTest .

Define an instance method that adds a new instance of the Menu model.

Call the assertEqual() method of the test class that compares the string representation of the newly added object with the anticipated value.

For example:

#TestCase class
class MenuItemTest(TestCase):
    def test_get_item(self):
        item = MenuItem.objects.create(title="IceCream", price=80, inventory=100)
        self.assertEqual(item, "IceCream : 80")

Step 4

Open a command terminal in VS Code. While in the project container directory, run the test with the following command:

python manage.py test

Check the result of the test if it returns as OK .

Step 5

Open the test_views.py file in tests folder.

Write a MenuViewTest class that subclasses the TestCase class.

Use the setup() method to add a few test instances of the Menu model.

Next, add another test_getall() instance method to retrieve all the Menu objects added for the test purpose.

The retrieved objects must serialized, so make sure the method runs assertions to check if the serialized data equals the response.

Run the test again with the command python manage.py test and verify if the test returns as OK .

Conclusion

In this exercise, you created and ran the unit tests to test the model and view for the Menu API.